package models

import (
	"fmt"
	"github.com/toolkits/pkg/logger"
	"gorm.io/gorm"
)

type SysUser struct {
	*gorm.Model
	ID       int64  `json:"ID"`
	UserName string `json:"user_name"`
	Password string `json:"-"`
	Email    string `json:"email"`
	Phone    string `json:"phone"`
	Role     string `json:"role"`
}

func (u *SysUser) Create(tx *gorm.DB) (userId int64, err error) {
	err = tx.Save(&u).Error
	if err != nil {
		return userId, err
	}
	return u.ID, nil
}

func (u *SysUser) UpdateUserByID(tx *gorm.DB) (err error) {
	err = tx.Where("id = ?", u.ID).Updates(&u).Error
	if err != nil {
		return err
	}
	return nil
}

func (u *SysUser) SelectUserById(tx *gorm.DB) (sysUser SysUser, err error) {
	err = tx.Where("id = ?", u.ID).Find(&sysUser).Error
	if err != nil {
		return sysUser, err
	}

	return sysUser, nil
}

// SelectUsers
// 根据条件查询用户。没有条件则查所有。
func (u *SysUser) SelectUsers(pageSize int64, pageNum int64, tx *gorm.DB) (sysUsers []SysUser, count int64, err error) {

	err = tx.Model(u).Where(u).Count(&count).Error
	if err != nil {
		logger.Error(err)
	}
	err = tx.Where(u).Limit(int(pageSize)).Offset(int((pageNum - 1) * pageSize)).Find(&sysUsers).Error
	if err != nil {
		logger.Error(err)
		return sysUsers, count, err
	}
	return sysUsers, count, err
}

func (u *SysUser) SelectUsersByUserName(pageSize int64, pageNum int64, tx *gorm.DB) (sysUsers []SysUser, count int64, err error) {
	userNameString := "%" + u.UserName + "%"
	err = tx.Model(u).Where("user_name like ?", userNameString).Count(&count).Error
	if err != nil {
		logger.Error(err)
	}
	err = tx.Where("user_name like ?", userNameString).Limit(int(pageSize)).Offset(int((pageNum - 1) * pageSize)).Find(&sysUsers).Error
	if err != nil {
		logger.Error(err)
		return sysUsers, count, err
	}
	return sysUsers, count, err
}

func (u *SysUser) SelectUserByUserName(tx *gorm.DB) (sysUser SysUser, err error) {
	err = tx.Where("user_name = ?", u.UserName).Find(&sysUser).Error
	if err != nil {
		logger.Error(err)
		return sysUser, err
	}
	return sysUser, err
}

func (u *SysUser) DeleteUser(tx *gorm.DB) (err error) {
	err = tx.Delete(&u).Error
	if err != nil {
		return err
	}
	return nil
}

func (u *SysUser) CountUsers(tx *gorm.DB) (count int64, err error) {
	fmt.Printf("------ u -----------\n%+v\n", u)
	a := SysUser{}
	b := *u
	err = tx.Model(b).Where(b).Find(&a).Count(&count).Error
	if err != nil {
		logger.Error(err)
	}
	fmt.Printf("a:%+v\n===== %d =====\n", a, count)
	fmt.Printf("-------- u ---------\n%+v\n", u)
	return count, err
}
